<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert
        title="商品添加信息"
        type="info"
        show-icon
        center
        :closable="false"
      ></el-alert>
      <!-- steps步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="AddFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- tabs导航栏 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择框 -->
              <el-cascader
                clearable
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  checkStrictly: 'true',
                  value: 'cat_id',
                  label: 'cat_name',
                  children: 'children'
                }"
                @change="HandleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单数据 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyCateList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyCateList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- upload上传图片组件 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button type="primary" class="addButton" @click="addClick"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览dialog -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewUrl" alt class="previewDialog" />
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";
export default {
  name: "Add",
  data() {
    return {
      activeIndex: "0",
      // 添加表单数据
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        // 上传的图片临时路径（对象）
        pics: [],
        // 商品介绍
        goods_introduce: "",
        // 商品参数的数组
        attrs: []
      },
      // 参数列表
      cateList: [],
      //动态参数列表
      manyCateList: [],
      // 静态属性列表
      onlyCateList: [],
      // 上传图片路径
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 图片请求headersObj对象
      headersObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      //预览图片的url
      previewUrl: "",
      // 图片预览dialog的控制显示与隐藏
      previewVisible: false,
      // 验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称!", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格!", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量!", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量!", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类!", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    //获取分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status == 200) {
        this.cateList = res.data;
      } else {
        this.$message.error("获取参数列表失败!");
      }
    },
    // 级联选择器变化触发函数
    HandleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    // tabs标签即将离开进入下一个tabs的钩子函数
    beforeLeave(activeName, oldActiveName) {
      if (this.addForm.goods_cat.length !== 3 && oldActiveName === "0") {
        this.$message.error("请选择分类!");
        return false;
      }
    },
    // tabs点击事件
    async tabClick() {
      // 点击了商品参数tabs
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cataId}/attributes`,
          {
            params: {
              sel: "many"
            }
          }
        );
        if (res.meta.status == 200) {
          this.$message.success("获取商品参数成功!");
          res.data.forEach(element => {
            element.attr_vals =
              element.attr_vals.length === 0
                ? []
                : element.attr_vals.split(",");
          });
          this.manyCateList = res.data;
          console.log(res.data);
        } else {
          this.$message.error("获取商品参数失败!");
          console.log(res.meta.msg);
        }
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cataId}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );
        if (res.meta.status == 200) {
          this.$message.success("获取商品参数成功!");
          this.onlyCateList = res.data;
        } else {
          this.$message.error("获取商品参数失败!");
          console.log(res.meta.msg);
        }
      }
    },
    // 显示图片事件
    handlePreview(file) {
      // 将url取出来
      this.previewUrl = file.response.data.url;
      //显示图片预览dialog
      this.previewVisible = true;
      console.log(file);
    },
    // 移除图片事件
    handleRemove(file) {
      // 获取需要移除图片的path
      const tmp_path = file.response.data.tmp_path;
      // 在当前pics数组中找到移除的图片
      const i = this.addForm.pics.findIndex(item => item.pics === tmp_path);
      // 移除图片
      this.addForm.pics.splice(i, 1);
      console.log(this.addForm);
    },
    //上传成功的钩子函数
    handSuccess(res) {
      // 拼接得到一个图片信息对象
      const picsInfo = res.data.tmp_path;
      // 将得到的图片信息保存到addform中
      this.addForm.pics.push(picsInfo);
      // console.log(res);
      // console.log(this.addForm);
    },
    // 添加商品信息
    addClick() {
      this.$refs.AddFormRef.validate(async vid => {
        if (!vid) {
          return this.$message.error("请输入必要的表单项!");
        }
        const cloneFrom = _.cloneDeep(this.addForm);
        cloneFrom.goods_cat = cloneFrom.goods_cat.join(",");
        this.manyCateList.forEach(item => {
          const formInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(",")
          };
          this.addForm.attrs.push(formInfo);
        });
        this.onlyCateList.forEach(item => {
          const formInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };
          this.addForm.attrs.push(formInfo);
        });
        cloneFrom.attrs = this.addForm.attrs;
        console.log(cloneFrom);
        const { data: res } = await this.$http.post("goods", cloneFrom);
        if (res.meta.status == 201) {
          this.$message.success("添加商品成功!");
          this.$router.push("/goods");
        } else {
          this.$message.error("添加商品失败!");
        }
      });
    }
  },
  created() {
    this.getCateList();
  },
  components: {},
  computed: {
    cataId() {
      if (this.addForm.goods_cat.length == 3) {
        return this.addForm.goods_cat[2];
      } else {
        return null;
      }
    }
  },
  beforeMount() {},
  mounted() {},
  watch: {}
};
</script>
<style lang="less" scoped>
.el-step {
  margin: 15px 10px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewDialog {
  width: 100%;
}
.addButton {
  margin-top: 15px;
}
</style>
